<?php defined('BASEPATH') || exit('No direct script access allowed');

class Crontab extends Front_Controller
{
	public function __construct()
	{
		parent::__construct();
	}

	//--------------------------------------------------------------------

	/**
	 * Displays the homepage of the Bonfire app
	 *
	 * @return void
	 */
	public function index($to = 'World')
	{
		echo "Hello {$to}!".PHP_EOL;
	}//end index()

    /*
     * 400 电话记录更新，每个小时更新
     */
    public function updateTiNet($start = 0) {
        $get = $this->input->get();
        $startTime = isset($get['start_time']) ? $get['start_time'] : date("Y-m-d H:i:s", strtotime("-1 hour"));
        $endTime = isset($get['end_time']) ? $get['end_time'] : date("Y-m-d H:i:s");
        $limit = isset($get['limit']) ? $get['limit'] : 100;
        $seed = 'udfandtinet';
        $post_url = "http://puruan.ccic2.com/interfaceAction/cdrIbInterface!listCdrIb.action";
        $postData = array(
                        'userName'      => 'admin',
                        'pwd'           => md5("2a5ef8484e0fb13a76cf43389518baf5".$seed),
                        'seed'          => $seed,
                        'enterpriseId'  => '3002702',
                        'startTime'     => $startTime,
                        'endTime'       => $endTime,
                        'limit'         => $limit,
                        'start'         => $start,
                    );
        dump($postData);
        // $post_url .= '?'.http_build_query($postData, NULL, '&');
        $this->load->library('curl', $post_url);
        $this->curl->post($postData);
        $returnStr = $this->curl->execute();
        $data = json_decode($returnStr);
        if ($data->result == 'success') {
            // 加载模型
            $this->load->model('buildings/buildingphonelog_model', 'buildingPhoneLog_model');
            $this->load->model('phone/phone_model');
            $this->load->model('channel/channel_model');
            // 获取楼盘移动端分机号数据
            $phoneArr = $this->phone_model->select('number,building_code,channel_id')->where(array('platform'=>2))->find_all();
            $codePhoneArr = null;
            if (is_array($phoneArr)) {
                foreach ($phoneArr as $val) {
                    $channel = $this->channel_model->find($val->channel_id);
                    $codePhoneArr[$val->number] = array('building_code'=>$val->building_code, 'channel_code'=>$channel->code);
                }
            }
            // $codePhoneArr['4000625650'] = array('building_code'=>'jd-yhn', 'channel_code'=>'baidu');
            // $codePhoneArr['4000151057'] = array('building_code'=>'jd-yhn', 'channel_code'=>'baidu');

            $dataArr = $data->msg->data;
            $paging = $data->msg->paging;
            // dump($dataArr);
            if (!is_array($dataArr)) exit('400接口无数据');
            foreach ($dataArr as $val) {
                if (!empty($val->userField)) {
                    // pc端数据
                    $userFieldArr = $this->convertUrlQuery(urldecode($val->userField));
                    if (isset($userFieldArr['phone_log_id'])) {
                        $buildingCode = isset($userFieldArr['building_code']) ? $userFieldArr['building_code'] : null;
                        $phoneLogId = $userFieldArr['phone_log_id'];
                        $upData['status'] = $val->status;
                        $upData['total_duration'] = $val->totalDuration;
                        $upData['ti_unique_id'] = $val->uniqueId;
                        $this->buildingPhoneLog_model->update($phoneLogId, $upData);
                        echo $phoneLogId;
                        dump($upData);
                    }
                } else {
                    // 移动端数据
                    if ((is_array($codePhoneArr) && isset($codePhoneArr[$val->hotline])) || isset($codePhoneArr[$val->queueName]) ) {
                        $buildingCode = isset($codePhoneArr[$val->hotline]) ? $codePhoneArr[$val->hotline]['building_code'] : $codePhoneArr[$val->queueName]['building_code'];
                        $channelCode = isset($codePhoneArr[$val->hotline]) ? $codePhoneArr[$val->hotline]['channel_code'] : $codePhoneArr[$val->queueName]['channel_code'];
                        $reData['building_log_id'] = 0;
                        $reData['event_id'] = 0;
                        $reData['ti_unique_id'] = $val->uniqueId;
                        $reData['building_code'] = $buildingCode;
                        $reData['channel_code'] = $channelCode;
                        $reData['telphone'] = $val->customerNumber;
                        $reData['status'] = $val->status;
                        $reData['total_duration'] = $val->totalDuration;
                        $reData['event'] = 1;
                        $reData['platform'] = 2;
                        $reData['created_on'] = $val->startTime;
                        dump($reData);
                        $this->buildingPhoneLog_model->db->replace($this->buildingPhoneLog_model->get_table(), $reData);
                    }
                }
                // dump($val);
            }
            $startData = $paging->start + $paging->pageSize;
            if ($paging->totalSize > $startData) {

            }
            dump($paging);
        } else if ($data->result == 'error') {
            // 数据获取失败
            exit($data->msg);
        }
    }

    public function urlQuery() {
        dump($this->convertUrlQuery("hi=from&view_id=12&cookie=fjdisjdia"));
    }

    protected function convertUrlQuery($query) {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
    public function dianhuaBlack(){
        $this->load->model('black_model');
        $get_url =  "http://120.26.112.32:8898/cms/adDataAction.do?method=getBlackListData";
        $get = $this->load->library('curl', $get_url);
        $returnStr = $this->curl->execute();
        $data = json_decode($returnStr);
        $arr = $data->data;
        foreach ($arr as $key => $value) {
            $phone = $value->phone;
            $res = $this->black_model->find_by("phone",$phone);
            if(!$res){
                $this->black_model->insert($value);
            }
        }
        
    }

    /**
     * 定时执行邮件队列
     * @return string
     * @author zephan <zephanliu@gmail.com>
     */
    public function processQueueEmail() {
        $this->load->library('emailer/emailer');
        $this->emailer->enable_debug(true);

        // Use ob to catch output designed for CRON only
        ob_start();
        $success = $this->emailer->process_queue();
        ob_end_clean();

        if (! $success) {
            echo $this->emailer->debug_message;
        } else {
            echo '发送成功';
        }

    }
    /**
     * 定时抓取项目前一天信息数据
     * @author fengchen <fengchen@usuretech.com>
     * @time 2016/11/4
     */
    public function getProjectStatisticsData(){

        //查询出所有的在投放的楼盘
        $this->load->library( 'curl');
        $this->load->model('mohe/mhorder_model');
        $this->load->model('mohe/mhpredata_model');
        $this->load->model('buildings/buildingsyuyue_model');
        $this->load->model('black_model');

        $dataOn = $mhorder_model->where("status = 1 and delete = 0")->find_all();
        if($dataOn){
            foreach ($dataOn as $key => $value) {
                $buildingCode = $value->code;
                $getData['method'] = 'getProjectStatisticsData';
                $getData['PARAMS'] = '{"date":"'.date("Y-m-d",strtotime("-1 day")).'","projectCode":"'.$buildingCode.'"}';

                $get_url = 'http://120.26.112.32:8898/cms/adDataAction.do?'.http_build_query($getData, NULL, '&');
                $returnStr = $this->curl->_simple_call('get',$get_url);
                $returnData = json_decode($returnStr, true);
                $data = $returnData['data'];
                if(empty($data)){
                    $insertData = array(
                        'order_id' => $value->id,
                        'building_id' => $value->building_id,
                        'building_code' => $buildingCode,
                        'curday'=>date("Y-m-d", strtotime("-1 day")),
                    );
                }
                //构造数据
                $insertData = array(
                        'order_id' => $value->id,
                        'building_id' => $value->building_id,
                        'building_code' => $buildingCode,
                        'click' => $data[0]['clickNum'],
                        'show' => $data[0]['showNum'],
                        'curday'=>$data[0]['currday']

                );
                // 加入前一天的线索数
                $datestamp = strtotime("-1 day");
                $cluesWhere = " type != 1 and building_code = '$curCode' and created_on >= '".date("Y-m-d 00:00:00",$datestamp)."' AND created_on <= '".date("Y-m-d 23:59:59",$datestamp)."'";
                $info = $this->buildingsyuyue_model->find_all_by($cluesWhere);
                if($info){
                    foreach ($info as $key => $value) {
                        $res = $this->black_model->find_by( ['phone' => $value->telphone] );
                        if( !$res ){ $cluesData[] = $value; }
                    }
                    $insertData['clues'] = !empty($cluesData) ? count($cluesData) : 0;
                }
                $this->mhpredata_model->insert($insertData);
            }
        }
    }
    /**
     * 调取爬虫库楼盘信息数据接口
     * @author fengchen <fengchen@usuretech.com>
     * @time 2016/11/8
     */
    public function loupanDicLingxi(){
        //获取接口请求令牌
        $this->load->library('curl');
        $this->load->model('mohe/mhshortinfo_model');
        //调取爬虫库楼盘信息数据
        $buildingUrl = "http://download.dmp.usuretech.com:41235/dmp/loupan/loupanDicLingxi.json";
        $returnbuildings = $this->curl->_simple_call('get', $buildingUrl);
        $buildingsArr = json_decode($returnbuildings, true);
        //对比数据
        $localDatas = $this->mhshortinfo_model->select('dmp_building_code')->find();
        if(empty($localDatas)){
            $this->mhshortinfo_model->insert_batch($buildingsArr);
        }else{
            foreach ($localDatas as $k => $v) {
                $localCodeArray[] = $v->dmp_building_code;
            }
            foreach ($buildingsArr as $key => $value) {
                $code = $value->dmp_building_code;
                if(!in_array($code, $localCodeArray)){
                    $this->mhshortinfo_model->insert($value);
                }
            }
        }
        exit("更新完成");   
    }


}
/* end ./application/controllers/crontab.php */
